<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import { userInfoService, userUploadAvatarService } from '@/api/user'
const userStore = useUserStore()
const Avatar = ref()
const imgUrl = ref(userStore.user.user_pic)
const uploadable = ref(true)
const uploadRef = ref()

const getUserInfo = async () => {
  const res = await userInfoService()
  console.log(res)
  Avatar.value = res.data.data.user_pic
}
getUserInfo()
const onUploadFile = (file) => {
  uploadable.value = false
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    imgUrl.value = reader.result
  }
}
const onUpdateAvatar = async () => {
  await userUploadAvatarService(imgUrl.value)
  await userStore.getUser()
  ElMessage({ type: 'success', message: '更换头像成功' })
  getUserInfo()
}
</script>
<template>
  <div>
    更换头像

    <el-upload
      ref="uploadRef"
      class="avatar-uploader"
      :limit="1"
      :auto-upload="false"
      :on-change="onUploadFile"
    >
      <el-button
        @click="uploadRef.$el.querySelector('input').click()"
        :inline="false"
        :icon="Plus"
        type="primary"
        >选择图片</el-button
      >
      <el-button
        @click="onUpdateAvatar"
        :inline="false"
        :icon="Upload"
        type="success"
        :disabled="uploadable"
        >上传头像</el-button
      >
      <template #trigger>
        <img v-if="imgUrl" :src="imgUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </template>
    </el-upload>
  </div>
</template>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
